package com.zhxymm.book.controllers;

import com.zhxymm.book.dao.NewBookRepository;
import com.zhxymm.book.dao.UserAccountRepository;
import com.zhxymm.book.entity.NewBook;
import com.zhxymm.book.entity.UserAccount;
import com.zhxymm.book.service.NewBookService;
import com.zhxymm.book.service.UserAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping("newBooks")
public class NewBookController {

    @Autowired
    NewBookService newBookService;

    @Autowired
    UserAccountService userAccountService;
    @Autowired
    UserAccountRepository userAccountRepository;

    @GetMapping
    public String displayNewBooks(Model model){
        List<NewBook> newBooks = newBookService.getAll();
        model.addAttribute("newBooks",newBooks);
        return "newBooks/list-newBooks";
    }

    @GetMapping("/new")
    public String displayNewBookForm(Model model){

        NewBook aNewBook = new NewBook();
        List<UserAccount> userAccounts = userAccountService.getAll();
        model.addAttribute("newBook",aNewBook);
        model.addAttribute("allUserAccounts",userAccounts);
        return "newBooks/new-newBook";
    }

    @PostMapping("/save")
    public String createNewBook(Model model, @RequestParam List<Long> userAccounts,NewBook newBook){
        newBookService.save(newBook);

        return "redirect:/newBooks"; //使用重定位防止重复提交
    }

    @GetMapping("/update")
    public String displayNewBookUpdateForm(@RequestParam("id")long theId,Model model){
        NewBook theNewBook = newBookService.findByNewBookId(theId);
        model.addAttribute("newBook",theNewBook);
        return "newBooks/new-newBook";
    }

    @GetMapping("/delete")
    public String deleteNewBook(@RequestParam("id")long theId,Model model){
        NewBook theNewBook = newBookService.findByNewBookId(theId);
        newBookService.delete(theNewBook);
        return "redirect:/newBooks";
    }
}